<template>
  <div v-loading="loading" element-loading-text="请艾特机器人授权..." class="content">
    <el-input v-model="uid" placeholder="账号ID">
      <template #prepend>UID</template>
    </el-input>
    <HandDrawnCard
      variant="default"
      size="medium"
      @click="handleLogin"
      style="text-align: center"
    >
      登录
    </HandDrawnCard>
  </div>
</template>

<script lang="ts">
import { Options, Vue } from "vue-class-component";
import { ref } from "vue";
import { ElDialog, ElInput, ElButton, ElLoading } from "element-plus";
import { callApi } from "@/tool/server";
import { useStore } from "vuex";
import HandDrawnCard from "@/components/HandDrawnCard.vue";
@Options({
  components: {
    ElDialog,
    ElInput,
    ElButton,
    HandDrawnCard,
  },
  props: {
    visible: Boolean,
  },
})
export default class Login extends Vue {
  uid = ref("");
  loading = false;
  store = useStore();
  handleLogin() {
    this.loading = true;
    this.store.commit("clearToken");
    callApi("Login", {
      account: String(this.uid),
    })
      .then(async (_res) => {
        if (!_res) {
          return;
        }
        this.store.commit("setToken", _res.token);
        // 轮询checkLogin
        while (true) {
          const res = await this.checkLogin(_res.token);
          if (res) {
            this.$emit("update:visible", true);
            break;
          } else if (typeof res == "number") {
            // 授权取消
            break;
          } else {
            // 等待100ms
            await new Promise((resolve) => setTimeout(resolve, 2000));
          }
        }
        // 在这里添加登录逻辑
      })
      .finally(() => {
        this.loading = false;
      });
  }
  async checkLogin(token: string) {
    const res = await callApi("Check", { _token: token });
    if (res) {
      return res.judge;
    }
    return 0;
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.content {
  width: 100%;
  animation: fadeIn 0.5s ease-in-out;
}
@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
.login-button {
  width: 80%;
  margin: 0 auto;
}
</style>
